package com.bcx.wind.workflow.imp.cmd.repositorycmd.windprocesscmd;

import com.bcx.wind.workflow.entity.WindProcess;
import com.bcx.wind.workflow.errorcontext.WindError;
import com.bcx.wind.workflow.interceptor.Command;
import com.bcx.wind.workflow.interceptor.CommandContext;
import com.bcx.wind.workflow.parser.ProcessBuilder;
import com.bcx.wind.workflow.parser.ProcessBuilderFactory;

import static com.bcx.wind.workflow.core.constant.ProcessStatus.RELEASE;
import static com.bcx.wind.workflow.message.ErrorCode.PROCESS_QUERY_NULL;
import static com.bcx.wind.workflow.message.ErrorCode.QUERY_FILTER_NULL;

/**
 * 通过流程定义ID 查询流程定义
 *
 * @author zhanglei
 */
public class QueryProcessOneCommand implements Command<WindProcess> {

    /**
     * 流程定义ID
     */
    private String processId;

    /**
     * 执行数据
     */
    private CommandContext commandContext;

    public QueryProcessOneCommand(String processId){
        this.processId = processId;
    }

    @Override
    public WindProcess executor(CommandContext context) {
        try{
            this.commandContext = context;
            return this.execute();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    private WindProcess execute(){
        if(this.processId == null){
            WindError.error(QUERY_FILTER_NULL,null);
        }
        WindProcess windProcess = this.commandContext.getConfiguration().getProcess(this.processId);
        if(windProcess == null) {
            windProcess = this.commandContext.access().getProcessDefinitionById(this.processId);
            if(windProcess == null){
                WindError.error(PROCESS_QUERY_NULL,null,this.processId);
            }

            if (windProcess != null && RELEASE.equals(windProcess.getStatus())) {
                ProcessBuilder processBuilder = ProcessBuilderFactory.getBuilder(windProcess.getContent());
                processBuilder.buildProcess(windProcess.getId());
                windProcess.processModel(processBuilder.getProcessModel());
                this.commandContext.getConfiguration().addProcessCache(windProcess);
            }
        }
        return windProcess;
    }

}
